package sk.mka.phd.files.reader.load.arbitrary;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.log4j.Logger;
import sk.mka.phd.files.reader.load.AbstractDataLoadFile;
import sk.mka.phd.files.reader.load.ILoadData;

/**
 *
 * @author bracek
 * @date Jun 29, 2010
 */
public class ArbitraryDataLoadFileImpl extends AbstractDataLoadFile implements ILoadData {

    private final static Logger log = Logger.getLogger(ArbitraryDataLoadFileImpl.class);
    protected ArrayList<Object> linesArrayList = new ArrayList<Object>();
    public int colsMaxLength = 0;
    public int linesMaxLength = 0;

    public ArbitraryDataLoadFileImpl(final String finalPath, final String separator) {
        super(finalPath, separator);
    }

    @Override
    public final void loadData() {
        Object[] subStr;
        try {
            final DataInputStream in = openInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line

            while ((strLine = br.readLine()) != null) {
                //craete new ArrayList which will hold column data
                ArrayList<Object> columnArrayList = new ArrayList<Object>();
                // Print the content on the console
                log.debug(strLine);
                if (!strLine.equals("")) {
                    subStr = strLine.split(separator);
                    columnArrayList.addAll(Arrays.asList(subStr));
                    if (columnArrayList.size() > colsMaxLength) {
                        colsMaxLength = columnArrayList.size();
                    }
                    linesArrayList.add(columnArrayList);
                }
            }
            //Close the input stream
            in.close();
        } catch (Exception e) {
            //Catch exception if any
            log.error("Error: " + e.getMessage());
        }

        linesMaxLength = linesArrayList.size();
    }

    @Override
    public void printData() {
        for (Object object : linesArrayList) {
            ArrayList<Object> col = (ArrayList<Object>) object;
            for (Object object1 : col) {
                System.out.print(object1 + "\t");
            }
            System.out.print("\n");
        }
    }

    @Override
    public final ArrayList<Object> getLines() {
        return linesArrayList;
    }

    public final int getColsMaxLength() {
        return colsMaxLength;
    }

    public final int getLinesMaxLength() {
        return linesMaxLength;
    }
}
